<template>
    <div class="container" v-loading="loading">
        <span style="font-size: 18px; color: black">
            <span style="font-weight: bolder; font-size: 18px">计算逻辑:</span>
            {{ chartData.calculateLogic }}
        </span>
        <div class="operate">
            <el-checkbox :checked="selectResultLine" @change="selectResultLineChange">计算结果折线图</el-checkbox>
            <el-checkbox :checked="selectBrValueLine" @change="selectBrValueLineChange">分支值折线图</el-checkbox>
            <el-checkbox :checked="selectPie" @change="selectPieChange">饼图</el-checkbox>
            <el-checkbox :checked="selectBar" @change="selectBarChange">柱状图</el-checkbox>
        </div>
        <div class="search-operate">
            <el-checkbox v-model="reqVO.curResult" @change="handleChange('curResult')">当前结果</el-checkbox>
            <el-form label-width="100px" class="search-operate1" ref="reqVO" v-model="reqVO">
                <el-form-item label="选择产品" prop="reFundCode">
                    <RiskCustomSelect
                        id="fund"
                        :selectKeys="reqVO.reFundCode"
                        :dataSource="reFundCodeValueOptionsTemp"
                        :showSelectAll="true"
                        :showSearch="true"
                        style="margin-left: 5px"
                        @customSelectReturn="customSelectReturn($event, 'reFundCode')"
                        :disabled="reqVO.curResult"
                        :key="key + 'key'"
                    ></RiskCustomSelect>
                </el-form-item>
                <el-form-item label="选择条目" prop="entryCodes">
                    <RiskCustomSelect
                        id="entry"
                        :selectKeys="reqVO.entryCodes"
                        :dataSource="entryCodesValueOptionsTemp"
                        :showSelectAll="false"
                        :showSearch="true"
                        style="margin-left: 5px"
                        @customSelectReturn="customSelectReturn($event, 'entryCodes')"
                        :disabled="reqVO.curResult"
                        :key="key + 'key'"
                    ></RiskCustomSelect>
                </el-form-item>
                <el-form-item label="计算日期">
                    <div style="display: flex">
                        <el-date-picker
                            name="date1"
                            v-model="reqVO.calculateDateStart"
                            align="right"
                            placeholder="开始日期"
                            :picker-options="startDatePicker"
                            value-format="yyyyMMdd"
                            format="yyyy-MM-dd"
                            @change="calculateDateStartChange"
                            size="mini"
                            :disabled="reqVO.curResult"
                        >
                        </el-date-picker>
                        <span>-</span>
                        <el-date-picker
                            name="date2"
                            v-model="reqVO.calculateDateEnd"
                            align="right"
                            placeholder="结束日期"
                            :picker-options="endDatePicker"
                            value-format="yyyyMMdd"
                            format="yyyy-MM-dd"
                            size="mini"
                            :disabled="reqVO.curResult"
                        >
                        </el-date-picker>
                    </div>
                </el-form-item>
            </el-form>
            <div>
                <el-button name="查询" type="primary" @click="chartQuery" size="mini" style="margin: 0 10px">查询</el-button>
                <el-button name="重置" @click="chartReset" size="mini">重置</el-button>
            </div>
        </div>
        <el-row>
            <el-col :span="12">
                <el-card class="box-card">
                    <div ref="resultLine" style="width: 580px; height: 300px" v-show="selectResultLine && state.isResultLine"></div>
                    <div name="resultLine" v-show="!state.isResultLine" style="font-weight: 800; padding-top: calc(25vh - 65px)">
                        <el-tooltip placement="top">
                            <div slot="content">计算结果折线图目前仅支持:单条目</div>
                            <span> 查询条件不支持查看计算结果折线图 </span>
                        </el-tooltip>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card class="box-card">
                    <div ref="BrValueLine" style="width: 580px; height: 300px" v-show="selectBrValueLine && state.isBrValueLine"></div>
                    <div name="BrValueLine" v-show="!state.isBrValueLine" style="font-weight: 800; padding-top: calc(25vh - 65px)">
                        <el-tooltip placement="top">
                            <div slot="content">分支值折线图目前仅支持:单条目单产品</div>
                            <span> 查询条件不支持查看分支值折线图</span>
                        </el-tooltip>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
                <el-card class="box-card">
                    <div name="pieChart" ref="Pie" style="width: 580px; height: 300px" v-show="selectPie"></div>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card class="box-card">
                    <div name="barChart" ref="Bar" style="width: 580px; height: 300px" v-show="selectBar"></div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import * as ECharts from 'echarts';
import XEUtils from 'xe-utils';
import DictionConstUtil from '@/utils/diction-const-util';
import RiskCustomSelect from '@/common/components/risk-custom-select.vue';
@Component({
    name: 'StaticResultChart',
    components: {
        RiskCustomSelect,
    },
})
export default class StaticResultChart extends Vue {
    @Prop() transToResultDetail;
    private loading: boolean = true;
    private reFundCodeValueOptions: any[] = [];
    private entryCodesValueOptions: any[] = [];

    key: number = -1;
    // 数据暂存数组
    private reFundCodeValueOptionsTemp: any[] = [];
    private entryCodesValueOptionsTemp: any[] = [];
    // 重置数据
    private resetData = {};
    // 展示图表
    private selectResultLine: boolean = true;
    private selectBrValueLine: boolean = true;
    private selectPie: boolean = true;
    private selectBar: boolean = true;

    // private currentEnd: boolean = true; // 当前结果(默认为启用：那条触警的产品和规则)
    // 图表总数据
    private chartData = {};

    private reqVO = {
        calculateDateEnd: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        calculateDateStart: XEUtils.toDateString(new Date(), 'yyyyMM') + '01',
        reFundCode: [],
        entryCodes: [],
        curResult: true,
    };
    private state: any = {
        // 查询条件不支持的情况
        isResultLine: true,
        isBrValueLine: true,
        // 图表数据
        calculateLogic: '',
        resultLine: [
            {
                data: [],
                type: 'line',
                emphasis: { focus: 'series' },
                smooth: '0.5',
            },
        ],
        resultLineLegend: {},
        brValueLine: [
            {
                data: [],
                type: 'line',
                emphasis: { focus: 'series' },
                smooth: '0.5',
            },
        ],
        brValueLineLegend: {},
        pie: {
            complianceTotal: '',
            warningTotal: '',
            examineTotal: '',
            prohibitTotal: '',
            errorTotal: '',
        },
        bar: {
            compliance: [],
            warning: [],
            examine: [],
            prohibit: [],
            error: [],
        },
        calculateDate: [],
    };

    async mounted() {
        this.resetData = XEUtils.clone(this.reqVO, true);
        await this.getFundInfo();
        await this.getEntryListInfo();
        this.getChartData();
        this.loading = false;
    }

    // 获取产品信息
    private getFundInfo() {
        return new Promise((resolve, reject) => {
            DictionConstUtil.FNFundInfo()
                .then((res: any) => {
                    this.reFundCodeValueOptionsTemp = res.map(item => {
                        item.dictKey = item.fundCode;
                        item.dictKeyName = item.fundName;
                        return item;
                    });
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
    }

    // 下拉多选框
    customSelectReturn(values, paramName: string) {
        if (paramName == 'reFundCode') {
            this.reqVO.reFundCode = values;
        } else if (paramName == 'entryCodes') {
            this.reqVO.entryCodes = values;
        }
        this.handleChange(paramName);
    }

    // 获取选择条目
    private getEntryListInfo() {
        return new Promise((resolve, reject) => {
            this.$axios
                .get('/static/getEntryList')
                .then((res: any) => {
                    this.entryCodesValueOptionsTemp = res.map(item => {
                        item.dictKey = item.entryCode;
                        item.dictKeyName = item.entryName;
                        return item;
                    });
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
    }

    // 获取图表数据
    private getChartData(): void {
        let req = this.reqVO.curResult
            ? {
                  ...this.reqVO,
                  entryKey: this.transToResultDetail.entryKey,
              }
            : this.reqVO;
        this.$axios.post('/static/result/chart', req).then((res: any) => {
            if (res !== undefined && res.bar !== undefined && res.bar.calculateDate.length !== 0) {
                this.chartData = res;
                this.handleReceiveParam0(this.chartData);
            } else {
                this.yh_message_warn('未能查询到符合条件的结果');
            }
        });
    }

    /**
     * 接收后端返回json对象,传入参数
     * 判断后端返回参数
     */
    private handleReceiveParam0(res: any): void {
        let calculateLogic = res.calculateLogic || '';
        let resultLineLegend = res.resultLineLegend || [];
        let resultLine = (res.resultLine || []).map(item => {
            let color = '#' + ('00000' + ((Math.random() * 16777215 + 0.5) >> 0).toString(16)).slice(-6);
            return {
                type: 'line',
                emphasis: { focus: 'series' },
                smooth: '0.5',
                data: item.data,
                name: item.name,
                itemStyle: {
                    normal: {
                        color: color,
                        lineStyle: {
                            color: color,
                        },
                    },
                },
                markLine: {
                    symbol: 'circle', // 当前标识
                    // symbol: 'none',
                    data: item.thresholdValue.map((item, index) => {
                        return {
                            yAxis: item,
                            lineStyle: {
                                // type: 'solid',
                                color: 'red',
                            },
                            label: {
                                fontSize: 10,
                                padding: [-10 + -25 * index, -20, 15, -120 + 20 * index],
                                position: 'end',
                                formatter: '阈值' + (index + 1) + '：' + this.conversion(item),
                            },
                        };
                    }),
                },
            };
        });

        this.state.calculateLogic = calculateLogic;
        this.state.calculateDate = res.bar.calculateDate;
        this.state.pie = res.pie;
        this.state.bar = res.bar;
        this.state.resultLineLegend = resultLineLegend;
        this.state.resultLine = resultLine;
        this.state.brValueLineLegend = res.brValueLineLegend || [];
        this.state.brValueLine = (res.brValueLine || []).map(item => {
            return {
                type: 'line',
                emphasis: { focus: 'series' },
                smooth: '0.5',
                data: item.data,
                name: item.name,
            };
        });

        if (res.brValueLineLegend === undefined || res.brValueLine === undefined) {
            this.state.isBrValueLine = false;
        } else {
            this.state.isBrValueLine = true;
        }

        if (res.resultLineLegend === undefined || res.resultLine === undefined) {
            this.state.isResultLine = false;
        } else {
            this.state.isResultLine = true;
        }

        this.resultLineInit();
    }

    // 渲染图表
    private resultLineInit(): void {
        ECharts.init(this.$refs.resultLine).setOption({
            title: {
                // 标题组件
                text: '计算结果折线图'.split('').join('\n'),
                left: 'left',
                right: '20px',
                top: 'middle',
                textStyle: { fontSize: 15 },
            },
            tooltip: { trigger: 'axis' },
            grid: {
                left: '10%',
            },
            legend: {
                data: this.state.resultLineLegend,
                // data:
                //     ['产品编号:2002'],
                bottom: 0,
                type: 'scroll',
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: this.state.calculateDate,
            },
            yAxis: {
                type: 'value',
                name: '计算结果',
                axisLabel: {
                    // margin: 2,
                    formatter: value => this.conversion(value),
                },
            },
            series: this.state.resultLine,
            // series: [
            //     {
            //         data: [150],
            //         type: 'line',
            //         emphasis: { focus: 'series' },
            //         smooth: '0.5',
            //     }
            // ]
        });
        ECharts.init(this.$refs.BrValueLine).setOption({
            title: {
                text: '分支值折线图'.split('').join('\n'),
                left: 'left',
                right: '20px',
                top: 'middle',
                textStyle: { fontSize: 15 },
            },
            tooltip: { trigger: 'axis' },
            legend: {
                data: this.state.brValueLineLegend,
                bottom: 0,
                type: 'scroll',
            },
            grid: {
                left: '10%',
            },
            color: ['#0A84FF', '#13C2C2', '#EB3197'],
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: this.state.calculateDate,
            },
            yAxis: {
                type: 'value',
                name: '分支值',
                axisLabel: {
                    formatter: value => this.conversion(value),
                },
            },
            series: this.state.brValueLine,
        });
        ECharts.init(this.$refs.Pie).setOption({
            title: { text: '触警数量扇形图'.split('').join('\n'), left: 'left', right: '20px', top: 'middle', textStyle: { fontSize: 15 } },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/> {b} : {c} ({d}%)',
            },
            legend: {
                data: ['合规', '警告', '送审', '禁止', '错误'],
                bottom: 0,
            },
            grid: {
                left: '10%',
            },
            color: ['#87D068', '#FFA500', '#ffe600', '#D53A35', '#334B5C'],
            series: [
                {
                    name: '静态风险报告',
                    type: 'pie',
                    radius: '45%',
                    center: ['50%', '60%'],
                    data: [
                        {
                            name: '合规',
                            customType: '1',
                            value: this.state.pie.complianceTotal,
                        },
                        {
                            name: '警告',
                            customType: '2',
                            value: this.state.pie.warningTotal,
                        },
                        {
                            name: '送审',
                            customType: '3',
                            value: this.state.pie.examineTotal,
                        },
                        {
                            name: '禁止',
                            customType: '4',
                            value: this.state.pie.prohibitTotal,
                        },
                        {
                            name: '错误',
                            customType: '5',
                            value: this.state.pie.errorTotal,
                        },
                    ],
                    itemStyle: {
                        normal: {
                            label: { show: true, formatter: '{b} : {c} ({d}%)' },
                            labelLine: { show: true },
                        },
                    },
                },
            ],
        });
        ECharts.init(this.$refs.Bar).setOption({
            title: {
                text: '每日触警统计柱状图'.split('').join('\n'),
                left: 'left',
                right: '20px',
                top: 'middle',
                textStyle: { fontSize: 15 },
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow',
                },
            },
            legend: {
                data: ['合规', '警告', '送审', '禁止', '错误'],
                bottom: 0,
            },
            color: ['#87D068', '#FFA500', '#ffe600', '#D53A35', '#334B5C'],
            xAxis: [
                {
                    type: 'category',
                    axisTick: { show: false },
                    data: this.state.calculateDate,
                },
            ],
            grid: {
                left: '10%',
            },
            yAxis: [{ type: 'value' }],
            series: [
                {
                    name: '合规',
                    type: 'bar',
                    emphasis: { focus: 'series' },
                    data: this.state.bar.compliance,
                },
                {
                    name: '警告',
                    type: 'bar',
                    emphasis: { focus: 'series' },
                    data: this.state.bar.warning,
                },
                {
                    name: '送审',
                    type: 'bar',
                    emphasis: { focus: 'series' },
                    data: this.state.bar.examine,
                },
                {
                    name: '禁止',
                    type: 'bar',
                    emphasis: { focus: 'series' },
                    data: this.state.bar.prohibit,
                },
                {
                    name: '错误',
                    type: 'bar',
                    emphasis: { focus: 'series' },
                    data: this.state.bar.error,
                },
            ],
        });
    }

    // 图表显示
    private selectResultLineChange(): void {
        this.selectResultLine = !this.selectResultLine;
    }
    private selectBrValueLineChange(): void {
        this.selectBrValueLine = !this.selectBrValueLine;
    }
    private selectPieChange(): void {
        this.selectPie = !this.selectPie;
    }
    private selectBarChange(): void {
        this.selectBar = !this.selectBar;
    }

    // 日期处理
    startDatePicker = {
        disabledDate: time => {
            let minDate = new Date().getTime() - new Date().getDate() * 3600 * 1000 * 24;
            let maxDate = new Date().getTime();
            return time.getTime() > maxDate || time.getTime() < minDate;
        },
    };

    endDatePicker = {
        disabledDate: time => {
            const calculateDateStart =
                this.reqVO.calculateDateStart.substring(0, 4) +
                '-' +
                this.reqVO.calculateDateStart.substring(4, 6) +
                '-' +
                this.reqVO.calculateDateStart.substring(6, 8);
            let minDate = Date.parse(calculateDateStart);
            let maxDate = new Date().getTime();
            return time.getTime() > maxDate || time.getTime() < minDate - 3600 * 1000 * 24;
        },
    };

    // 日期处理
    private calculateDateStartChange(val: any): void {
        if (this.reqVO.calculateDateEnd < val) {
            this.reqVO.calculateDateEnd = null;
        }
    }

    // 查询
    private chartQuery(): void {
        if (!this.reqVO.calculateDateEnd || !this.reqVO.calculateDateStart) {
            this.yh_message_warn('请选择计算日期');
        } else {
            if (!this.reqVO['curResult'] && !this.reqVO['reFundCode'].length && !this.reqVO['entryCodes'].length) {
                this.yh_message_warn('未启用当前结果，那么产品和规则为必选项');
            } else {
                this.getChartData();
            }
        }
    }

    // 重置
    private chartReset(): void {
        (this.$refs['reqVO'] as any).resetFields();
        this.reqVO.curResult = false;
        this.reqVO.calculateDateEnd = null;
        this.reqVO.calculateDateStart = null;
    }

    // 当前结果勾选变化
    private handleChange(value: string): void {
        if (value === 'curResult') {
            this.reqVO.reFundCode = [];
            this.reqVO.entryCodes = [];
            this.key++;
        } else if (value === 'reFundCode' || value === 'entryCodes') {
            this.reqVO.curResult = false;
        }
    }

    // 折线图 y轴数值太大进行转换
    private conversion(value): string {
        if (value >= 10000 && value < 10000000) {
            value = value / 10000 + '万';
        } else if (value >= 10000000 && value < 100000000) {
            value = value / 10000000 + '千万';
        } else if (value >= 100000000) {
            value = value / 100000000 + '亿';
        }
        return value;
    }
}
</script>
<style lang="scss" scoped>
.container {
    .operate {
        display: flex;
        margin: 10px 0px;
    }
    .search-operate {
        line-height: 40px;
        display: flex;
        justify-content: start;
    }
    .search-operate1 {
        display: flex;
    }
    /deep/ .el-card__body {
        padding: 0px 20px !important;
    }
    /deep/ .el-form-item__label {
        color: #5c5e62 !important;
    }
    /deep/ .el-input {
        width: 140px;
    }
    .box-card {
        min-width: 580px;
        min-height: 300px;
        text-align: center;
    }
}
/deep/ .el-checkbox .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #409eff !important;
    &:after {
        border-color: #fff !important;
    }
}
/deep/ .el-checkbox__inner {
    border-color: #409eff;
}
.my-dropdown {
    height: 200px;
    overflow: auto;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    .search {
        width: 98%;
        height: 40px;
        margin-left: 2px;
        margin-right: 2px;
        .input-container {
            display: inline-block;
            width: 90%;
            line-height: 0;
            /deep/ .el-input__inner {
                height: 25px;
            }
        }
    }
    .el-checkbox {
        display: block;
        margin: 0;
        line-height: 0;
    }
}
</style>
